package com.fubowen.reader.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import com.fubowen.reader.R
import com.fubowen.reader.adapter.SwipeDeleteCallback
import com.fubowen.reader.databinding.PublicTreeSelectedBinding
import com.fubowen.reader.db.model.Tree
import kotlinx.coroutines.launch


class TreeSelectedFragment : TreeFragment() {

    private lateinit var binding: PublicTreeSelectedBinding

    override val isEnableBreadcrumb = false
    override var isDialog = true

    override fun onItemClick(view: View, item: Tree, position: Int) {}

    override fun onItemButtonClick(view: View, item: Tree, position: Int) {
        when (item.status) {
            Tree.STATUS_RUNNING -> {
                item.status = Tree.STATUS_PAUSED
                cacheViewModel.stop(item)
            }

            Tree.STATUS_PAUSED -> {
                item.status = Tree.STATUS_RUNNING
                cacheViewModel.start(item)
            }
        }
    }

    override fun onSizeChanged(size: Int) {
        binding.title.text = getString(R.string.selected_title, size)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = PublicTreeSelectedBinding.inflate(inflater)
        super.initRecyclerView(binding.root)
        observerSelectedFlow()
        observerUpdateFlow()
        binding.submit.setOnClickListener { cacheViewModel.download() }
        binding.count.text = getString(R.string.coroutine_count, cacheViewModel.coroutineCountFlow.value)
        val callback = SwipeDeleteCallback {
            val position = layoutManager.getPosition(it.itemView)
            val item = adapter.currentList[position]
            item.status = Tree.STATUS_NOT_START
            item.isChecked = false
            cacheViewModel.update(item)
            cacheViewModel.delete(item)
            adapter.notifyItemRemoved(position)
        }
        val itemTouchHelper = ItemTouchHelper(callback)
        itemTouchHelper.attachToRecyclerView(recycler)
        return binding.root
    }

    private fun observerSelectedFlow() = lifecycleScope.launch {
        cacheViewModel.selectedFlow.collect {
            adapter.submitList(it)
        }
    }

    private fun observerUpdateFlow() = lifecycleScope.launch {
        cacheViewModel.updateFlow.collect { item ->
            val index = adapter.currentList.indexOfFirst { it.absolutePath == item.absolutePath }
            if (index != -1) {
                adapter.notifyItemChanged(index, item)
            }
        }
    }
}